﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleBuffer
{
    public class ConsoleBuffer : IDisposable
    {
        private static int defaultPoolSize;
        private static Stack<BufferedConsole> pool;

        private bool active;
        private BufferedConsole console;

        static ConsoleBuffer()
        {
            defaultPoolSize = 10;
            pool = new Stack<BufferedConsole>(defaultPoolSize);
            for (int i = 0; i < defaultPoolSize; i++)
            {
                pool.Push(new BufferedConsole());
            }
        }

        public ConsoleBuffer()
        {
            if (pool.Count != 0)
            {
                console = pool.Pop();
            }
            else
            {
                console = new BufferedConsole();
            }
            active = true;
        }

        public void Write(string msg)
        {
            if (!active)
            {
                throw new ObjectDisposedException(this.ToString());
            }
            console.Write(msg);
        }

        public void WriteLine(string msg)
        {
            if (!active)
            {
                throw new ObjectDisposedException(this.ToString());
            }
            console.WriteLine(msg);
        }

        public void Dispose()
        {
            console.Dispose();
            active = false;
            pool.Push(console);
        }
    }
}
